package com.springsecurity.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.GenericFilterBean;

import java.io.IOException;

@Component
public class ValidCodeFilter extends GenericFilterBean {
	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
		HttpServletRequest request=(HttpServletRequest)servletRequest;
		HttpServletResponse response=(HttpServletResponse)servletResponse;
		if ("POST".equalsIgnoreCase(request.getMethod())&&"/login".equals(request.getServletPath())) {
			String code = request.getParameter("code");
			String validCode=(String) request.getSession().getAttribute("validCode");
			if (!validCode.equalsIgnoreCase(code)) {
				request.getSession().setAttribute("msg","验证码错误");
				response.sendRedirect("/toLogin");
			}
		}
		filterChain.doFilter(request,response);
	}
}
